package com.example.springbootredis.service.impl;

import com.example.springbootredis.entiy.ShippingAddress;
import com.example.springbootredis.repository.ShippingAddressRepository;
import com.example.springbootredis.service.ShippingAddressService;
import jakarta.persistence.Cacheable;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class ShippingAddressServiceImpl implements ShippingAddressService {

    @Autowired
    private ShippingAddressRepository shippingAddressRepository;

    @Override
    public List<ShippingAddress>findByMemberId(Long memberId) {
        return shippingAddressRepository.findByMemberIdOrderByCreatedDateDesc(memberId);
    }

    @Override
    public Optional<ShippingAddress> findByIdAndMemberId(Long id, Long memberId) {
        return Optional.empty();
    }



    @Override
    public Optional<ShippingAddress> findById(Long id, Long memberId) {
        return shippingAddressRepository.findByIdAndMemberId(id, memberId);
    }

    @Override
    @Transactional
    public ShippingAddress save(ShippingAddress shippingAddress) {
        if(Boolean.TRUE.equals(shippingAddress.getIsDefault())){
            shippingAddressRepository.clearDefaultShippingAddressByMemberId(shippingAddress.getMemberId());
        }
        return shippingAddressRepository.save(shippingAddress);
    }
    @Override
    @Transactional
    public void deleteByIdAndMemberId(Long id, Long memberId) {
        if(shippingAddressRepository.existsByMemberIdAndIsDefault(id,true)){
            throw new IllegalArgumentException("默认地址不能删除");
        }
        shippingAddressRepository.deleteById(id);
    }
    @Override
    @Transactional
    public void setDefaultAddress(Long id, Long memberId) {
        shippingAddressRepository.clearDefaultAddress(memberId);

        Optional<ShippingAddress> address = shippingAddressRepository.findByIdAndMemberId(id, memberId);
    }
}
